const createError = require("http-errors")
const express = require("express")
const path = require("path")
const cookieParser = require("cookie-parser")
const logger = require("morgan")
const cors = require("cors")
const { expressjwt: jwt } = require("express-jwt")

const config = require("./config")

const middleware = require("./utils/middleware")
const indexRouter = require("./routes/index")
const usersRouter = require("./routes/user/")

const app = express()

// view engine setup
app.set("views", path.join(__dirname, "views"))
app.set("view engine", "jade")
// 自定义中间件
app.use(middleware.sendSuccessRespone)
app.use(middleware.sendErrorRespone)

app.use(
  cors({
    origin: true,
    methods: ["GET", "POST", "PUT", "DELETE"]
  })
)
app.use(logger("dev"))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, "public")))
app.use(express.static(path.join(__dirname, "/uploads/images")))
app.use(jwt({ secret: config.SECRET, algorithms: ["HS256"] }).unless({ path: ["/api/login"] }))

app.use("/api", indexRouter)
app.use("/api/users", usersRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// 错误中间件
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get("env") === "development" ? err : {}
  // 捕获表单校验相关报错
  if (err.isJoi) {
    return res.sendError(err.details[0].message, 500)
  }
  // 捕获校验token验证失败报错
  console.log(String(req.auth))
  if (err.name === "UnauthorizedError") {
    console.log(req.auth)
    return res.sendError("token认证失败", 401)
  }

  res.sendError(err.message, err.status || 500)
  next()
})

module.exports = app
